import { h, ref, defineComponent, nextTick } from 'vue'
import { Modal, Input } from 'ant-design-vue'
import { EditOutlined } from '@ant-design/icons-vue'

export const showRenameModal = (conversation, emit) => {
  const inputRef = ref()
  const inputValue = ref(conversation.label)

  const ModalContent = defineComponent({
    setup() {
      // 延迟让 Modal 真正挂载后再 focus
      setTimeout(() => {
        nextTick(() => {
          if (inputRef.value?.focus) {
            inputRef.value.focus()
            inputRef.value.select()
          }
        })
      }, 50) // 50ms 延迟通常足够

      return () =>
        h(Input, {
          ref: inputRef,
          value: inputValue.value,
          'onUpdate:value': (val) => (inputValue.value = val),
          placeholder: '请输入新名称',
          class: 'w-full',
        })
    },
  })

  Modal.confirm({
    centered: true,
    title: '重命名会话',
    icon: h(EditOutlined, { style: { color: '#000' } }),
    content: h(ModalContent),
    okText: '确认',
    cancelText: '取消',
    onOk: () => {
      const newName = inputValue.value.trim()
      if (newName && newName !== conversation.label) {
        emit('rename-conversation', conversation.key, newName)
      }
    },
  })
}
